<!--
 * @description: 
 * @Author: lal
 * @Date: 2020-08-02 10:36:58
 * @LastEditors: lal
 * @LastEditTime: 2020-11-18 11:15:12
-->
<template>
  <div>
    <div class="head">
      <p>
        计算规则：8:45~18:00<br />
        工作日不计算上班时间，下午7:00之前均为0 <br />
        周六周日全天按照480分钟（8h）计算，上下午各四个小时，减去上午和下午缺少的时间 <br />
        没有节假日得概念，如有自行计算 <br />
      </p>
      <p>
        <el-switch
          v-model="season"
          class="mr20"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="冬季"
          inactive-text="夏季"
          active-value="winter"
          inactive-value="summer"
          @change="seasonChanged"
        >
        </el-switch>
        <el-button type="primary" @click="updateDays">更新时间</el-button>
      </p>
    </div>
    <el-table
      :data="daysBymonth"
      border
      height="500"
      :summary-method="getSummaries"
      show-summary
      :row-class-name="tableRowClassName"
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="name" label="日期">
        <template #default="{row}">
          {{ row.date | formatDate }}

          <span v-if="row.d == new Date().getDate()">当前时间</span>
        </template>
      </el-table-column>
      <el-table-column prop="amount1" label="上班时间">
        <template #default="{row}">
          <el-time-picker
            v-model="row.realWorkTime"
            placeholder="任意时间点"
            :clearable="clearable"
            @change="val => timeChange(val, row, 'realWorkTime')"
          >
          </el-time-picker>
        </template>
      </el-table-column>
      <el-table-column prop="amount2" label="下班时间">
        <template #default="{row}">
          <el-time-picker
            v-model="row.realOffWorkTime"
            placeholder="任意时间点"
            :clearable="clearable"
            @change="val => timeChange(val, row, 'realOffWorkTime')"
          >
          </el-time-picker>
        </template>
      </el-table-column>
      <el-table-column prop="overtime" label="加班时长">
        <template #default="{row}">
          {{ row.overtime }}
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import dayjs from "dayjs";
import ElectronStore from "electron-store";
const store = new ElectronStore();
export default {
  data() {
    return {
      value1: "",
      clearable: false,
      value2: new Date(2016, 9, 10, 18, 40),
      season: "winter",
      seasonObj: {
        winter: {
          offWorkHour: [17, 30, 0],
          validOffWorkHour: [18, 30, 0],
        },
        summer: {
          offWorkHour: [18, 0, 0],
          validOffWorkHour: [19, 0, 0],
        },
      },
      daysBymonth: [],
    };
  },
  methods: {
    tableRowClassName({ row }) {
      if (row.d == new Date().getDate()) {
        return "success-row";
      }
      return "";
    },
    seasonChanged(val) {
      store.set("currSeason", val);
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "加班总时长";
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += " 分钟";
        } else {
          sums[index] = "N/A";
        }
      });

      return sums;
    },

    /**
     * [timeChange description]
     *
     * @param   {[type]}  val  [val 选择后的时间值]
     * @param   {[type]}  row  [row 表格行数据]
     * @param   {[type]}  key  [key 更改的字段，上班时间还是下班时间]
     *
     * @return  {[type]}       [return description]
     */
    timeChange(val, row, key) {
      let { offWorkHour } = this.seasonObj[this.season];

      let { week, y, m, d } = row;
      let timeDiff;
      let h = dayjs(val).hour(),
        minute = dayjs(val).minute(),
        s = dayjs(val).second();
      row[key] = new Date(y, m, d, h, minute, s).getTime();
      if (week == 0 || week == 6) {
        let amOvertime = 240,
          pmOvertime = 240,
          amtimeDiff,
          pmtimeDiff;
        //周六周日时间
        if (dayjs(row.realOffWorkTime).isBefore(new Date(y, m, d, ...offWorkHour))) {
          // 下午下班之前走了
          if (dayjs(row.realOffWorkTime).isBefore(new Date(y, m, d, 12, 0, 0))) {
            // 下班时间在12点之前 按照结束时间减去开始时间
            timeDiff = dayjs(row.realOffWorkTime).diff(dayjs(row.realWorkTime), "minute");
          } else {
            // 下班时间在12点之后 下班点之前
            amtimeDiff = dayjs(row.realWorkTime).diff(dayjs(row.workTime), "minute"); //上午加班去掉得时间
            pmtimeDiff = dayjs(row.offWorkTime).diff(dayjs(row.realOffWorkTime), "minute"); //下午加班去掉得时间
            pmOvertime = pmOvertime - pmtimeDiff > 0 ? pmOvertime - pmtimeDiff : 0;
            timeDiff = amOvertime - amtimeDiff + pmOvertime;
          }
        } else {
          // 下午下班之后才走的
          amtimeDiff = dayjs(row.realWorkTime).diff(dayjs(row.workTime), "minute");
          // 若为负值，则上午没加班，清0
          amOvertime = amOvertime - amtimeDiff > 0 ? amOvertime - amtimeDiff : 0;
          // 下午才开始加班 这里好像有问题
          pmtimeDiff = dayjs(row.realOffWorkTime).diff(dayjs(row.offWorkTime), "minute");
          timeDiff = amOvertime + pmOvertime + pmtimeDiff;
        }
      } else {
        timeDiff = dayjs(row.realOffWorkTime).diff(dayjs(row.validOffWorkTime), "minute");
      }
      row.overtime = timeDiff > 0 ? timeDiff : 0;
      store.set("daysBymonth", JSON.stringify(this.daysBymonth));
    },
    /**
     * [description] 创建[更新]当月时间
     */
    updateDays() {
      let date = new Date(),
        y = date.getFullYear(),
        m = date.getMonth();
      // date.getMinutes
      let firstDay = new Date(y, m, 1).getDate();
      let lastDay = new Date(y, m + 1, 0).getDate();
      let days = [];

      let { offWorkHour, validOffWorkHour } = this.seasonObj[this.season];
      for (let index = firstDay; index <= lastDay; index++) {
        let date = new Date(y, m, index).getTime();
        let week = dayjs(date).day();
        let realOffWorkTime = new Date(y, m, index, ...offWorkHour).getTime();
        if (week == 0 || week == 6) {
          // 休息日
          realOffWorkTime = new Date(y, m, index, 8, 45, 0).getTime();
        }
        days.push({
          date,
          week,
          y,
          m,
          d: index,
          workTime: new Date(y, m, index, 8, 45, 0).getTime(),
          realWorkTime: new Date(y, m, index, 8, 45, 0).getTime(),
          offWorkTime: new Date(y, m, index, ...offWorkHour).getTime(),
          validOffWorkTime: new Date(y, m, index, ...validOffWorkHour).getTime(),
          realOffWorkTime,
          overtime: 0,
        });
      }
      this.daysBymonth = days;
      store.set("daysBymonth", JSON.stringify(this.daysBymonth));
    },
  },
  created() {
    let daysBymonth = store.get("daysBymonth");
    let currSeason = store.get("currSeason");
    if (currSeason) {
      this.season = currSeason;
    }
    if (daysBymonth) {
      this.daysBymonth = JSON.parse(daysBymonth);
      debugger;
    } else {
      this.updateDays();
    }
  },
  mounted() {},
};
</script>
<style lang="scss">
.el-table .success-row {
  background: #f0f9eb;
}
</style>
<style scoped lang="scss">
.head {
  display: flex;
  justify-content: space-between;
}

.mr20 {
  margin-right: 20px;
}
</style>
